<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.LoginName" placeholder="输入名称查询" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="Id" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="账户名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.loginName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center">
        <template slot-scope="{row}">
          <span>{{ row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column label="省市区" align="center">
        <template slot-scope="{row}">
          <span>{{ row.province+row.city+row.area }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :page-sizes="[20]" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="账户名称" prop="loginName">
          <el-input v-model="temp.loginName" :disabled="dialogStatus==='create'?false:true" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="temp.level" @change="onLevel">
            <el-option v-for="item in levels" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.level" label="省市区">
          <el-cascader
            v-model="temp.address"
            :options="sigleAddress"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle } from '@/api/manager'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { mapGetters } from 'vuex'

export default {
  name: 'User',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
      },
      temp: { level: '' },
      levels: [
        { key: '省级管理员', display_name: '省级管理员' },
        { key: '地市管理员', display_name: '地市管理员' },
        { key: '区县管理员', display_name: '区县管理员' },
      ],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      sigleAddress: [],
      rules: {
        loginName: [{ required: true, message: '必填项', trigger: 'blur' }],
        name: [{ required: true, message: '必填项', trigger: 'blur' }],
        password: [{ required: true, message: '必填项', trigger: 'blur' }]
      },
    }
  },
  computed: {
    ...mapGetters([
      'addressOptions'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const { address } = this.temp
          this.temp.province = address[0] || ''
          this.temp.city = address[1] || ''
          this.temp.area = address[2] || ''
          createArticle(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.address = [row.province, row.city, row.area].filter((item) => item)
      this.transAddress(this.temp.level)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const { address } = this.temp
          this.temp.province = address[0] || ''
          this.temp.city = address[1] || ''
          this.temp.area = address[2] || ''
          const tempData = Object.assign({}, this.temp)
          updateArticle(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('保存成功')
          })
        }
      })
    },
    notifyMessage(info) {
      this.$notify({
        title: info,
        type: 'success',
        duration: 2000
      })
    },
    handleDelete(row, index) {
      deleteArticle({ loginName: row.loginName }).then(() => {
        this.getList()
        this.notifyMessage('删除成功')
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    transAddress(val) {
      if (val === '省级管理员') {
        this.sigleAddress = this.addressOptions.map((item) => {
          return { label: item.label, value: item.value }
        })
      } else if (val === '地市管理员') {
        this.sigleAddress = this.addressOptions.map((item) => {
          const _child = item.children.map((item1) => {
            return { label: item1.label, value: item1.value }
          })
          return { ...item, children: _child }
        })
      } else {
        this.sigleAddress = this.addressOptions
      }
    },
    onLevel(val) {
      if (this.temp.address) {
        this.temp.address = ''
        this.temp.province = ''
        this.temp.city = ''
        this.temp.area = ''
      }
      this.transAddress(val)
    }
  }
}
</script>
